package algebra.query.pd;

import java.util.HashSet;
import java.util.Set;

import option.QueryKeywords;
import utils.Display;

import entities.role.Role;

public class PdConjunction extends ProjDesc {

	private final ProjDesc sub1, sub2;
	
	public PdConjunction(ProjDesc pd1, ProjDesc pd2){
		this.sub1  =pd1;
		this.sub2 = pd2;
	}
	
	public ProjDesc getSubPd1(){
		return sub1;
	}
	public ProjDesc getSubPd2(){
		return sub2;
	}

	@Override
	public boolean projectOnSomeFeature() {
		return sub1.projectOnSomeFeature() || sub2.projectOnSomeFeature();
	}

	@Override
	public Set<Role> extractFeatures() {
		Set<Role> fs = new HashSet<Role>();
		fs.addAll(sub1.extractFeatures());
		fs.addAll(sub2.extractFeatures());
		return fs;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((sub1 == null) ? 0 : sub1.hashCode());
		result = prime * result + ((sub2 == null) ? 0 : sub2.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof PdConjunction))
			return false;
		PdConjunction other = (PdConjunction) obj;
		if (sub1 == null) {
			if (other.sub1 != null)
				return false;
		} else if (!sub1.equals(other.sub1))
			return false;
		if (sub2 == null) {
			if (other.sub2 != null)
				return false;
		} else if (!sub2.equals(other.sub2))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "(" + this.sub1.toString() + Display.ANDUNICODE
				+ this.sub2.toString() + ")";
	}

	@Override
	public String toSerializedString() {
		return "(" + QueryKeywords.PD_CONJUNCTION + " "
				+ this.sub1.toSerializedString() + " "
				+ this.sub2.toSerializedString() + ")";
	}

	@Override
	public boolean moreSpecificThan(ProjDesc that) {
		if(that instanceof PdConjunction){
			ProjDesc sub1 = ((PdConjunction) that).sub1, 
					sub2 = ((PdConjunction) that).sub2;
			boolean same = true;
			same &= this.sub1.moreSpecificThan(sub1)
					|| this.sub2.moreSpecificThan(sub1);
			same &= this.sub1.moreSpecificThan(sub2)
					|| this.sub2.moreSpecificThan(sub2);
			return same;
		}
		return false;
	}

	@Override
	public boolean hasConjunctiveFeature() {
		return this.sub1.hasConjunctiveFeature() || this.sub2.hasConjunctiveFeature();
	}
	
	
}
